package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.exception.NoStockException;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.vo.LockStockResult;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
//        //1、判断如果还没有这个库存记录新增
//        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
//        if(entities == null || entities.size() == 0){
//            WareSkuEntity skuEntity = new WareSkuEntity();
//            skuEntity.setSkuId(skuId);
//            skuEntity.setStock(skuNum);
//            skuEntity.setWareId(wareId);
//            skuEntity.setStockLocked(0);
//            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
//            //1、自己catch异常
//            //TODO 还可以用什么办法让异常出现以后不回滚？高级
//            try {
//                R info = productFeignService.info(skuId);
//                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");
//
//                if(info.getCode() == 0){
//                    skuEntity.setSkuName((String) data.get("skuName"));
//                }
//            }catch (Exception e){
//
//            }
//
//
//            wareSkuDao.insert(skuEntity);
//        }else{
//            wareSkuDao.addStock(skuId,wareId,skuNum);
//        }
//        判断是否有库存记录？新增：更新
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(wareSkuEntities== null || wareSkuEntities.size() == 0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            wareSkuEntity.setSkuName("");

            try {
                R info = productFeignService.info(skuId);
                Map<String, Object> data = (Map<String, Object>) info.get("skuInfo");

                if (info.getCode() == 0) {
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {

            }

            wareSkuDao.insert(wareSkuEntity);
        }else{

            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(sku -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            vo.setSkuId(sku);
//            查询sku总库存量
            Long count = baseMapper.getSkuStock(sku);
            vo.setHasStock(count != null && (count > 0));
            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为订单锁定库存
     * @param vo
     * @return
     */

    @Transactional
    @Override
    public boolean orderLockStock(WareSkuLockVo vo) {

//        找到有库存的商品
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWhereHasStock> collect = locks.stream().map(item -> {
            SkuWhereHasStock stock = new SkuWhereHasStock();
            Long skuId = item.getSkuId();

            stock.setSkuId(skuId);
//            查询有该商品库存的仓库id
            List<Long> wareIds = wareSkuDao.ListWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());

        for (SkuWhereHasStock hasStock : collect) {
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds == null || wareIds.size() ==0){
//                没有仓库有库存
                throw new NoStockException(skuId);
            }
            boolean flag = false;
            for(Long wareId : wareIds){
                long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count == 1){
                    flag = true;
                    break;
                }
            }
            if(!flag) throw new NoStockException(hasStock.getSkuId());
        }
//        全部锁定成功

        return true;
    }

    @Data
    class SkuWhereHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}